function aminvar = simannealargminVar(vbeta, Dstart, levels, iterations)
    
    %levels determines the size of the "neighborhood" from which d is drawn
    %iterations is the number of draws

    global n Vstar
    
    
       
        
       Dstar=Dstart;
       Vstar= vbeta(Dstar);
       d=Dstart;
       vnew=Vstar;
       vinitial=Vstar;
       
       
       
       for i=1:iterations
           %temperature function; possibly calibrate by choice of premultiplier
           T=  .5*vinitial * (iterations-i)/iterations;
           %generate new d by choosing a random subset of "levels"
           %coordinates, and randomly switching them with proba .5
           dnew=d(:);
           p = randperm(n,levels);
           dnew(p(:)) = mod(dnew(p(:)) + binornd(1,.5,levels,1), 2);
           
           %evaluate Var at new d
           vold=vnew;
           vnew = vbeta(d);
           
           %storing best d - not part of annealing proper
           if vnew < Vstar
                Dstar=dnew;
                Vstar=vnew; 
           end
           
           %decide whether to stay or move
           if (exp(-(vnew-vold)/T) > rand)
               d=dnew;
           else
               vnew=vold;
           end
           
       end
       
       
 
aminvar=Dstar;       


return



